<?php

namespace App\Http\Controllers;

use App\Exceptions\AuthException;
use App\Exceptions\FobbidenException;
use App\Http\Requests\FeedbackRequest;
use App\Services\FeedbackService;
use Illuminate\Http\Request;

/**
 * 留言板 Controller
 */
class FeedbackController extends Controller
{
    /**
     * 留言分页列表
     *
     * @param Request $request
     * @param FeedbackService $feedbackService
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request, FeedbackService $feedbackService)
    {
        $page = $request->input('page', 1);
        $page_size = $request->input('page_size', 0);

        $count = $feedbackService->countFeedback();
        $data = $feedbackService->getPaginatedFeedback($page_size)
            ->appends(['page' => $page]);

        return view('feedback.index', ['data' => $data, 'count' => $count]);
    }

    /**
     * 创建页面
     *
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create()
    {
        return view('feedback.create');
    }

    /**
     * 添加留言
     *
     * @param FeedbackRequest $request
     * @param FeedbackService $feedbackService
     * @return array
     */
    public function store(FeedbackRequest $request, FeedbackService $feedbackService): array
    {
        $data = $request->only(['title', 'content']);

        try {
            $result = $feedbackService->storeFeedback($data);
            if (! $result) {
                return $this->error('添加留言失败，请重试');
            }

            return $this->success('添加留言成功');
        } catch (AuthException|FobbidenException $e) {
            return $this->error($e->getMessage(), $e->getCode());
        } catch (\Exception $e) {
            return $this->error('添加留言失败，请重试');
        }
    }
}
